package sf.database.util;

import sf.database.meta.ColumnMapping;
import sf.database.meta.TableMapping;

import java.util.Map;

public class SQLUtils {
    public static final String PLACEHOLDER = "?";

    /**
     * 通过数据库列名获取指定map中的key值(数据库关键字的处理)
     * @param map
     * @param columnName 数据库的列名
     * @return
     */
    public static ColumnMapping getColumnByDBName(TableMapping map, String columnName) {
        ColumnMapping o = map.getIgnoreCaseColumnMapping(columnName);
        if (o != null) {
            return o;
        }
        //以下为数据库关键字的处理
        o = map.getIgnoreCaseColumnMapping("`" + columnName + "`");
        if (o == null) {
            o = map.getIgnoreCaseColumnMapping("\"" + columnName + "\"");
        }
        if (o == null) {
            o = map.getIgnoreCaseColumnMapping("[" + columnName + "]");
        }
        return o;
    }

    /**
     * @param map
     * @param columnName
     * @param <T>
     * @return
     */
    public static <T> T getColumnByDBName(Map<?, T> map, String columnName) {
        T o = map.get(columnName);
        if (o != null) {
            return o;
        }
        //以下为数据库关键字的处理
        o = map.get("`" + columnName + "`");
        if (o == null) {
            o = map.get("\"" + columnName + "\"");
        }
        if (o == null) {
            o = map.get("[" + columnName + "]");
        }
        return o;
    }

    /**
     * 去除关键字的特殊字符
     * @param columnName
     * @return
     */
    public static String getNoWrapperColumnName(String columnName) {
        if (columnName.startsWith("`") && columnName.endsWith("`")) {
            columnName = columnName.replace("`", "");
        } else if (columnName.startsWith("\"") && columnName.endsWith("\"")) {
            columnName = columnName.replace("\"", "");
        } else if (columnName.startsWith("[") && columnName.endsWith("]")) {
            columnName = columnName.replace("[", "").replace("]", "");
        }
        return columnName;
    }

    public static String placeholder() {
        return PLACEHOLDER;
    }
}
